import room from "@/app/room"
import { creepDefaultMemory } from "@/app/spawn/constant"
import { roles } from "@/app/spawn/spawnRoles"
import { CreepConfig, CreepRole, RoleDatas } from "@/role/types/role"
import CreepController from "../controller"
import RoleRemoteWorker from "./remoteWorker"


class RoleRemoteManager {


    /**
     * 快死时的后事处理
     * 将资源存放在对应的地方
     * 存完了就自杀
     *
     * @param creep manager
     * @param sourceId 能量存放处
     */
    static deathPrepare(creep: Creep): false {
        if (creep.store.getUsedCapacity(RESOURCE_ENERGY) > 0) {

            if (creep.room.name != creep.memory.spawnRoom) {
                creep.goTo(new RoomPosition(25, 25, creep.memory.spawnRoom))
                return
            }

            const target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
                filter: s => (s.structureType == STRUCTURE_CONTAINER || s.structureType == STRUCTURE_STORAGE) && s.store.getFreeCapacity(RESOURCE_ENERGY) > 0
            })

            if (target) {
                creep.goTo(target.pos)
                creep.transfer(target, RESOURCE_ENERGY)
            }
            return
        }
        else {
            creep.suicide()
        }

        return false
    }



    static spawnRoomNames: string[] = ['E35S49', 'E39S52']
    static workRoomNames: string[][] = [['E35S48', 'E34S48'], ['E38S52']]
    static sourceIndexs: number[][][] = [[[0], [1, 2, 3]], [[0, 1]]]

    static roomNames: string[] = ['E35S48', 'E34S48']

    /**
     *
     * @param creep
     * @returns
     */
    static loop(creep: Creep) {

        if (creep.ticksToLive < 130) {
            RoleRemoteManager.deathPrepare(creep)
            return
        }

        // 获取creep名字后缀数字编号
        const creepIndex = parseInt(creep.name.split('_')[1])

        const spawnRoomIndex = RoleRemoteManager.spawnRoomNames.indexOf(creep.memory.spawnRoom)
        const roomNames = RoleRemoteManager.workRoomNames[spawnRoomIndex]
        const roomManagerIndexs = RoleRemoteManager.sourceIndexs[spawnRoomIndex]

        let roomName: string
        for (const index in roomManagerIndexs) {
            const indexs = roomManagerIndexs[index]

            for (const i in indexs) {
                if (indexs[i] == creepIndex) {
                    roomName = roomNames[index]
                    break
                }
            }
        }
        // console.log('spawnRoomIndex creepIndex roomName', spawnRoomIndex, creepIndex, roomName)

        const memoryData: RoleDatas[CreepRole.RemoteManager] = creep.memory.data as RoleDatas[CreepRole.RemoteManager]

        if (!memoryData) {
            creep.log('memory error')
            return
        }

        if (!memoryData.workRoom || memoryData.workRoom != roomName) {
            memoryData.workRoom = roomName
        }

        if (creep.store.getFreeCapacity(RESOURCE_ENERGY) > 200 && creep.ticksToLive > 120) {

            const room = Game.rooms[memoryData.workRoom]
            if (!room || room.name != creep.room.name) {
                creep.goTo(new RoomPosition(25, 25, memoryData.workRoom))
                return
            }

            if (!memoryData.resourceId && !memoryData.sourceId) {
                const droppedEnergy = CreepController.managerFindDropSource(creep, 200)
                if (droppedEnergy) {
                    memoryData.resourceId = droppedEnergy.id
                }
                else {
                    const container = CreepController.findContainer(creep, 400)
                    if (container) {
                        memoryData.sourceId = container.id
                    }
                }
            }

            if (memoryData.resourceId) {
                const target = Game.getObjectById(memoryData.resourceId) as Resource
                if (target) {
                    const resource = target as unknown as Resource
                    if (resource) {
                        if (resource.amount > 0) {
                            creep.say('=>res')
                            creep.goTo(target.pos, { range: 1 })
                            const status = creep.pickup(resource)
                            if (status == OK) {
                                delete memoryData.resourceId
                            }
                            return
                        }
                    }
                }
                delete memoryData.resourceId
            }

            if (memoryData.sourceId) {
                const container = Game.getObjectById(memoryData.sourceId) as StructureContainer
                if (container) {
                    if (container.store[RESOURCE_ENERGY] > 0) {
                        creep.say('=>con')
                        creep.goTo(container.pos, { range: 1 })
                        const status = creep.withdraw(container, RESOURCE_ENERGY)
                        if (status == OK) {
                            delete memoryData.sourceId
                        }
                        return
                    }
                }
                delete memoryData.sourceId
            }

            // creep.goTo(new RoomPosition(25, 25, roomName))
        }
        else {
            // 没有能量且快死了，自杀释放资源
            if (creep.ticksToLive <= 55 && creep.store[RESOURCE_ENERGY] == 0) {
                creep.suicide()
                return
            }

            // 边走边修
            if (creep.store[RESOURCE_ENERGY] > 0) {
                const roads = creep.pos.findInRange(FIND_STRUCTURES, 2, {
                    filter: s => s.structureType == STRUCTURE_ROAD && s.hits < s.hitsMax
                })
                if (roads && roads[0]) {
                    creep.repair(roads[0])
                }
            }

            const homeRoomName: string = 'E35S49'
            if (memoryData.workRoom == RoleRemoteManager.roomNames[0]) {
                //
                // Room 1 外矿1
                if (creep.room.name != homeRoomName) {
                    const status = creep.goTo(new RoomPosition(39, 23, 'E35S49'))
                    return
                }
            }
            else if (memoryData.workRoom == RoleRemoteManager.roomNames[1]) {
                //
                // Room 1 外矿2
                if (creep.room.name != RoleRemoteManager.roomNames[0]) {
                    const status = creep.goTo(new RoomPosition(25, 25, RoleRemoteManager.roomNames[0]))
                    return
                }
                if (!memoryData.sourceId) {
                    const container = Game.getObjectById('61983824615732b331be7d82') as StructureWithStore
                    if (container && container.store.getFreeCapacity(RESOURCE_ENERGY) > 0) {
                        memoryData.sourceId = container.id
                    }
                }
            }
            else if (memoryData.workRoom == RoleRemoteManager.workRoomNames[1][0]) {
                //
                // Room 2 外矿1
                if (creep.room.name != RoleRemoteManager.spawnRoomNames[1]) {
                    const status = creep.goTo(new RoomPosition(25, 25, RoleRemoteManager.spawnRoomNames[1]))
                    return
                }
            }

            if (!memoryData.sourceId) {
                const storeObj = CreepController.remoteManagerFindLinkContainer(creep)
                if (storeObj) {
                    memoryData.sourceId = storeObj.id
                }
            }

            if (memoryData.sourceId) {
                const target = Game.getObjectById(memoryData.sourceId) as StructureWithStore
                if (target) {
                    const status = creep.transfer(target, RESOURCE_ENERGY)
                    if (status == ERR_NOT_IN_RANGE) {
                        creep.goTo(target.pos)
                    }
                    else if (status == OK) {
                        delete memoryData.sourceId
                    }
                }
                delete memoryData.sourceId
            }
        }
    }
}

export default RoleRemoteManager
